//
//  SLPlaceholderTextView.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/30.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit

class SLPlaceholderTextView: UITextView {
    
    //MARK: - 属性
    //覆盖父类的属性 1.override 2.实现didSet
    //子类是对父类的扩展,属性赋值是先给父类赋值.再给子类
    override var text: String? {
        didSet {
            //有文本就隐藏
            placeholderLabel.hidden = self.hasText()
        }
    }
    ///字体大小
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    ///设置占位文本
    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        prepareUI()
        //代理: 1对1,要注意被覆盖,我们这里先设置然后被控制器覆盖了.所以只有控制器能监听到文字的改变
//        self.delegate = self
        //通知: 1对多.里面用通知.外面覆盖不了.外面用什么对我们没有干扰
        //object: 通知的发送者. nil:只要发送UITextViewTextDidChangeNotification就能监听到. object:指定对象发送的才能监听到
        //别人发送的通知不关心.只关心自己的文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    func textDidChange() {
        placeholderLabel.hidden = hasText()
    }
    
    private func prepareUI() {
        //添加子控件
        addSubview(placeholderLabel)
        
        //添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    }
    
    //MARK: - 懒加载
    //占位文本
     private lazy var placeholderLabel: UILabel = {
        //添加label
        let placeholderLabel = UILabel()
        placeholderLabel.font = UIFont.systemFontOfSize(15)
        placeholderLabel.textColor = UIColor.lightGrayColor()
        placeholderLabel.sizeToFit()
       
       return placeholderLabel
    }()
}

//MARK: - 扩展
//extension SLPlaceholderTextView: UITextViewDelegate {
//    //当文字发送改变时调用
//    func textViewDidChange(textView: UITextView) {
//        // textView.hasText()是否有文本  
//        //有文本就隐藏
//        placeholderLabel.hidden = textView.hasText()
//        
//    }
//}
